package com.mcptt.http.operator.sys;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import com.cloudptt.api.product.log.Log;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mcptt.comm.CommonFunc;
import com.mcptt.config.local.SysConfig;
import com.mcptt.config.model.McIdInfo;
import com.mcptt.config.model.McpttLoginInfo;
import com.mcptt.config.model.ServerInfo;
import com.mcptt.http.operator.IHttpOpCb;
import com.mcptt.http.operator.OkHttpUtils;

import android.os.Handler;
import android.os.Message;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SysHttpGetLoader implements Callback{
	private static final String HTTP_KEY = "http://";;
	private static final String Sub_Url_Get = "/xpoc/ue-udb-servaddr";
	private static final int ConnectionTimeout = 30 * 1000;
	private static final int SoTimeout = 30 * 1000;
	protected final static int OP_SUC = 0;
	protected final static int OP_FAILED = 1;
	private SysConfig config = null;
//	private String svrIp = null;
//	private String num = null;
//	private String pwd = null;

	protected IHttpOpCb callback = null;

	public SysHttpGetLoader(SysConfig config,IHttpOpCb callback)
	{
		this.config = config;
		this.callback = callback;
	}

	public void doHttpGet() {
//		final String url = HTTP_KEY + svrIp + Sub_Url_Get;


		new Thread(new Runnable(){
			@Override
			public void run() 
			{
				try {
					doHttpGetThread();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

	private void doHttpGetThread() throws Exception
	{
		if(config != null)
		{
			String svrIp = config.getHttpServerInfo().getIp();
			int port = config.getHttpServerInfo().getPort();
			String url = HTTP_KEY + svrIp + ":" + port + Sub_Url_Get;
			
			McpttLoginInfo mcpttLoginInfo = config.getMcpttLoginInfo();

			McIdInfo userInfo = mcpttLoginInfo.getMcIdInfo();
			String num = userInfo.getMcId();
			
			Log.debug(getClass(), "doHttpGetThread url = " + url + " num = " + num);
			Map<String, String> params = new HashMap<String, String>();
			params.put("AccntID", num);
			OkHttpUtils.getInstance().doPutJson(url, params, this);
		}
	}

	private void sendOpResultMsg(boolean isSuc,int cause)
	{
		if(isSuc)
		{
			Message msg = handler.obtainMessage(OP_SUC);
			msg.arg1 = cause;
			msg.sendToTarget();
		}
		else
		{
			Message msg = handler.obtainMessage(OP_FAILED);
			msg.arg1 = cause;
			msg.sendToTarget();
		}
	}

	protected Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what)
			{
			case OP_SUC:
				if(callback != null)
				{
					int cause = msg.arg1;
					callback.onOpResult(IHttpOpCb.Id_Get,true,cause,"");
				}
				break;
			case OP_FAILED:
				if(callback != null)
				{
					int cause = msg.arg1;
					callback.onOpResult(IHttpOpCb.Id_Get,false,cause,"");
				}
				break;
			}
		}
	};

	@Override
	public void onFailure(Call arg0, IOException arg1) {
		// TODO Auto-generated method stub
		sendOpResultMsg(false,70090);
	}

	@Override
	public void onResponse(Call arg0, Response response) {
		// TODO Auto-generated method stub
		if(response == null)
		{
			sendOpResultMsg(false,70091);
			return;
		}

		Log.debug(getClass(), "onResponse isSuccessful = " + response.isSuccessful());
		if(response.isSuccessful())
		{

			try 
			{
				InputStream  instreams = response.body().byteStream(); 
				String content = CommonFunc.convertStreamToString(instreams);//.convertStreamToString(instreams,"user_not_registered");
				Log.debug(getClass(), "onResponse Content = " + content);
				
				JsonParser jsonParser = new JsonParser();
				JsonObject obj = jsonParser.parse(content).getAsJsonObject();
				Log.debug(getClass(), "onResponse obj = " + obj);
				String ip = obj.get("ACEAddr").getAsString();
				int port = ServerInfo.Default_Svr_Port;//obj.get("UDBPort").getAsInt();
				Log.debug(getClass(), "onResponse ip = " + ip + " port = " + port);
				
				if(config != null
						&& ip != null
						&& ip.length() > 0
						&& port != 0)
				{
					config.setServerInfo(ip, port);
					sendOpResultMsg(true,0);
				}
				else
				{
					sendOpResultMsg(false,70092);
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				sendOpResultMsg(false,70090);
			}
		}
		else
		{
			sendOpResultMsg(false,70091);
			//	    notifyFailed(parserCallback,"readFromSvr code = " + code);
		}
	}
}
